﻿using EmailHelper.Model;
using Microsoft.Exchange.WebServices.Data;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;

namespace EmailHelper.Exchange
{
    /// <summary>
    /// Exchange接收帮助类
    /// </summary>
    public class EWSReceiveHelper
    {
        /// <summary>
        /// 获取收件箱指定邮件
        /// </summary>
        /// <param name="service"></param>
        /// <param name="pageSize">搜索操作返回的最大项目数。</param>
        /// <param name="offset">视图相对于基点的偏移量。 标识返回的项目页面的起始位置。</param>
        /// <returns></returns>
        public async static Task<List<EmailInfoExchange>> GetInbox(ExchangeService service, int pageSize, int offset)
        {
            try
            {
                List<EmailInfoExchange> lstEmails = new List<EmailInfoExchange>();
                //代表文件夹搜索操作中的视图设置。
                ItemView view = new ItemView(pageSize, offset);
                //FindItems方法下获取的没有Body属性
                FindItemsResults<Item> findResults = await service.FindItems(WellKnownFolderName.Inbox, SetFilter(), view);
                //FindItemsResults<Item> findResults = await service.bin(WellKnownFolderName.Inbox, SetFilter(), view);
                foreach (Item item in findResults.Items)
                {
                    //TextBody：获取item的文本body。 TextBody属性适用于从Exchange Server 2013开始的，面向Exchange Online和Exchange版本的客户端。
                    //使用 PropertySet 限制搜索结果
                    PropertySet properties = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.TextBody, ItemSchema.MimeContent);
                    //await item.Load(properties);
                    //await item.Load(PropertySet.IdOnly);


                    ItemId itemId = item.Id;
                    EmailMessage message = await EmailMessage.Bind(service, itemId, properties);

                    lstEmails.Add(new EmailInfoExchange()
                    {
                        ExchangeItemId = message.Id.ChangeKey,
                        body = message.MimeContent?.Content,
                        Mail_cc = message.DisplayCc,
                        Mail_from = message.LastModifiedName,
                        IsRead = message.IsNew,
                        Subject = message.Subject,
                        CreateOn = message.DateTimeCreated
                    });

                    //lstEmails.Add(new EmailInfo()
                    //{
                    //    ExchangeItemId = item.Id.ChangeKey,
                    //    body = item.Body.Text,
                    //    Mail_cc = item.DisplayCc,
                    //    Mail_from = item.LastModifiedName,
                    //    IsRead = item.IsNew,
                    //    Subject = item.Subject,
                    //    CreateOn = item.DateTimeCreated
                    //});
                }
                return lstEmails;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                return null;
            }
        }
        /// <summary>
        /// 过滤器,筛选今天的邮件
        /// </summary>
        /// <returns></returns>
        private static SearchFilter SetFilter()
        {
            List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
            //searchFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            //searchFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true));
            //筛选今天的邮件
            SearchFilter start = new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeCreated, Convert.ToDateTime(DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd 00:00:00")));
            SearchFilter end = new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeCreated, Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59")));
            searchFilterCollection.Add(start);
            searchFilterCollection.Add(end);
            SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection.ToArray());
            return filter;
        }


        /// <summary>
        /// 根据用户邮件地址返回用户的未读邮件数
        /// </summary>
        /// <param name="service"></param>
        /// <param name="email"></param>
        /// <returns></returns>
        public async static Task<int> GetUnReadMailCountByUserMailAddress(ExchangeService service, string email)
        {
            int unRead = 0;
            try
            {
                //该帐户无权模拟所请求的用户，查看 https://www.cnblogs.com/kennyliu/p/3771298.html
                service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, email); //模拟
                Folder folder = await Folder.Bind(service, WellKnownFolderName.Inbox);
                unRead = folder != null ? folder.UnreadCount : -1;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return unRead;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mailAccount"></param>
        /// <param name="allRecipient"></param>
        /// <param name="needRemoveKeys"></param>
        /// <returns></returns>
        public static Dictionary<string, string> GetContacts(string mailAccount, Dictionary<string, string> allRecipient, ref List<string> needRemoveKeys)
        {
            //需要Exchange拉取的收件人、抄送、密送  <key= mailAddress,value= name>
            Dictionary<string, string> needToPullDic = new Dictionary<string, string>();

            return needToPullDic;
        }


        /// <summary>
        /// 获取组下的人
        /// </summary>
        /// <param name="service"></param>
        /// <param name="groupAddress"></param>
        /// <returns></returns>
        public async static Task<List<ContactInfo>> GetContacts(ExchangeService service, string groupAddress)
        {
            List<ContactInfo> contactInfos = new List<ContactInfo>();

            ExpandGroupResults groupresult = await service.ExpandGroup(groupAddress); //展开由指定的组SMTP地址标识的组。
            foreach (EmailAddress email in groupresult?.Members)
            {
                switch (email.MailboxType)
                {
                    case MailboxType.Contact:
                    case MailboxType.Mailbox:
                        {
                            contactInfos.Add(new ContactInfo()
                            {
                                //获取Exchange对象的唯一ID。
                                Id = email.Id?.UniqueId,
                                Name = email.Name,
                                Address = email.Address,
                                EmailType = (int)MailboxType.Contact, //email地址的类型
                                RoutingType = email.RoutingType
                            });
                        }
                        break;
                    case MailboxType.ContactGroup:
                    case MailboxType.GroupMailbox:
                    case MailboxType.PublicFolder:
                    case MailboxType.PublicGroup:
                        {
                            contactInfos.Add(new ContactInfo()
                            {
                                //获取Exchange对象的唯一ID。
                                Id = email.Id.UniqueId,
                                Name = email.Name,
                                Address = email.Address,
                                EmailType = (int)MailboxType.ContactGroup,
                                RoutingType = email.RoutingType
                            });
                        }
                        break;
                }
            }
            return contactInfos;
        }


        /// <summary>
        /// 搜索联系人
        /// </summary>
        /// <param name="service"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public async static Task<List<ContactInfo>> ResolveName(ExchangeService service, string name)
        {
            List<ContactInfo> contactInfos = new List<ContactInfo>();
            //在默认联系人文件夹和/或全局地址列表（GAL）中查找名称与作为参数传递的名称匹配的联系人。
            NameResolutionCollection nameResolutions = await service.ResolveName(name, ResolveNameSearchLocation.DirectoryThenContacts, true);
           
            foreach (NameResolution resolution in nameResolutions)
            {
                switch (resolution.Mailbox.MailboxType)
                {
                    case MailboxType.ContactGroup:
                    case MailboxType.GroupMailbox:
                    case MailboxType.PublicFolder:
                    case MailboxType.PublicGroup:
                        {
                            contactInfos.Add(new ContactInfo()
                            {
                                //获取Exchange对象的唯一ID。
                                Id = resolution.Mailbox.Id?.UniqueId,
                                Name = resolution.Mailbox.Name,
                                Address = resolution.Mailbox.Address,
                                EmailType = (int)MailboxType.ContactGroup
                            });
                        }
                        break;
                    case MailboxType.Contact:
                    case MailboxType.Mailbox:
                        {
                            contactInfos.Add(new ContactInfo()
                            {
                                //获取Exchange对象的唯一ID。
                                Id = resolution.Mailbox.Id?.UniqueId,
                                Name = resolution.Mailbox.Name,
                                Address = resolution.Mailbox.Address,
                                EmailType = (int)MailboxType.Contact
                            });
                        }
                        break;
                }
            }
            return contactInfos;
        }

    }
}
